//
//  RHChoiceCityView.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/3/7.
//


#import "RHChoiceCityView.h"


@implementation RHCountryModel
+ (nullable NSDictionary<NSString *, id> *)modelCustomPropertyMapper
{
    return @{@"addressId":@"id"};
}
@end

@implementation RHStateModel
+ (nullable NSDictionary<NSString *, id> *)modelCustomPropertyMapper
{
    return @{@"addressId":@"id"};
}
@end

@implementation RHCityModel
+ (nullable NSDictionary<NSString *, id> *)modelCustomPropertyMapper
{
    return @{@"addressId":@"id"};
}
@end

@interface RHChoiceCityView()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *countryArr;//国家列表

@property (nonatomic ,strong) NSArray *stateArr;//省,州列表

@property (nonatomic ,strong) NSArray *cityArr;//城市列表

@property (nonatomic ,strong) RHCountryModel *countryModel;

@property (nonatomic ,strong) RHStateModel *stateModel;

@property (nonatomic ,strong) RHCityModel *cityModel;

@property (nonatomic ,strong) UIView *contentView;

@property (nonatomic ,strong) MASConstraint *bgViewTopConstraint;

@property (nonatomic ,strong) MASConstraint *bgViewBottomConstraint;


@property (nonatomic, strong) UIView *containView;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) NSMutableArray *labelArr;

@property (nonatomic, strong) NSMutableArray *selectArr;//当前选择的

@end
@implementation RHChoiceCityView

-(instancetype)init
{
    if(self = [super init]){
        [self setupUI];
    }
    return self;
}


- (void)setupUI{
    kWeakSelf;
    self.selectArr = [NSMutableArray array];
    [self setBackgroundColor:[UIColor.blackColor colorWithAlphaComponent:0]];
 
    UIView *touchView = [[UIView alloc] init];
    [touchView setBackgroundColor:UIColor.clearColor];
    [self addSubview:touchView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    touchView.userInteractionEnabled = YES;
    [touchView addGestureRecognizer:tap];
    
    UIView *contentView = kView;
    contentView.backgroundColor = UIColor.whiteColor;
    [self addSubview:contentView];
    self.contentView = contentView;
    
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        self.bgViewTopConstraint = make.top.equalTo(self.mas_bottom);
        make.height.offset(kUI_WINDOW_H*0.7);
    }];
    
    _titleLab = [[QMUILabel alloc] init];
    [_titleLab setText:@"请选择所在地区".rh_localized];
    _titleLab.numberOfLines = 0;
    [_titleLab setTextAlignment:NSTextAlignmentCenter];
    [_titleLab setFont:[UIFont systemFontOfSize:16]];
    [_titleLab setTextColor:FontColor(@"#969799")];
    _titleLab.backgroundColor = UIColor.whiteColor;
    [contentView addSubview:_titleLab];
    
    QMUIButton *sureBtn = [[QMUIButton alloc]init];
    [sureBtn setTitle:@"确定".rh_localized forState:UIControlStateNormal];
    sureBtn.titleLabel.font = kSYSTEMFONT(15);
    [sureBtn setTitleColor:FontColor(@"#3DBB91") forState:UIControlStateNormal];
    [contentView addSubview:sureBtn];
    
    //所选地区
    UIView *addressView = [self addressView];
    [contentView addSubview:addressView];
    [addressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(weakSelf.titleLab.mas_bottom);
        make.height.offset(50);
    }];
    
    
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = UIColor.whiteColor;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [contentView addSubview:_tableView];
    
    UIView *lineV = [[UIView alloc] init];
    [lineV setBackgroundColor:FontColor(@"#eeeeee")];
    [contentView addSubview:lineV];
    
    UIView *btnView = kView;
    btnView.backgroundColor = UIColor.whiteColor;
    [contentView addSubview:btnView];
    [btnView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
    }];
    
    
    [touchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    
    CGFloat btnWidth =  [sureBtn.titleLabel.text getStringWidthFont:sureBtn.titleLabel.font limitHeight:20];
    CGFloat titleWidth = (kUI_WINDOW_W - (30 + btnWidth)*2);
    
    [_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.height.mas_equalTo(49);
        make.top.mas_offset(0);
        make.width.offset(titleWidth);
    }];
    
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.titleLab);
        make.right.mas_offset(-15);
        make.height.offset(40);
    }];
    
    [lineV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(1);
        make.top.equalTo(weakSelf.titleLab.mas_bottom);
    }];
    
   
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(addressView.mas_bottom);
        make.left.right.mas_offset(0);
        make.bottom.mas_offset(0);
       
    }];
    
    contentView.layer.cornerRadius = 8;
    contentView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    
    [tap.rac_gestureSignal subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
//        if (weakSelf.choiceResultBlock) {
//            weakSelf.choiceResultBlock(nil);
//        }
        [weakSelf hidden];
    }];
  
    
    [[sureBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        
        if(weakSelf.countryModel && weakSelf.stateModel){
            NSMutableString *address = [NSMutableString string];
            NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
            [address appendString:weakSelf.countryModel.name];
            [address  appendFormat:@"/%@",weakSelf.stateModel.name];
            
            [paraDic setObject:@(weakSelf.countryModel.addressId) forKey:@"countryId"];
            [paraDic setObject:weakSelf.countryModel.name forKey:@"countryName"];
            [paraDic setObject:@(weakSelf.stateModel.addressId) forKey:@"stateId"];
            [paraDic setObject:weakSelf.stateModel.name forKey:@"stateName"];
            if (weakSelf.cityModel) {
                [address  appendFormat:@"/%@",weakSelf.cityModel.name];
                [paraDic setObject:@(weakSelf.cityModel.addressId) forKey:@"cityId"];
                [paraDic setObject:weakSelf.cityModel.name forKey:@"cityName"];
            }
            
            
            if (weakSelf.choiceResultBlock) {
                weakSelf.choiceResultBlock(address.copy,paraDic.copy);
            }
            [weakSelf hidden];
        }
    }];
    
    self.tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"No data" detailStr:@""];
}


- (void)hidden{
    kWeakSelf;
    [self.bgViewBottomConstraint uninstall];
    [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        self.bgViewTopConstraint = make.top.equalTo(self.mas_bottom);
        
    }];
    [UIView animateWithDuration:0.2 animations:^{
        [self setNeedsLayout];
        [self layoutIfNeeded];
        [self setBackgroundColor:[UIColor.blackColor colorWithAlphaComponent:0]];
    } completion:^(BOOL finished) {
        
        [self removeFromSuperview];
        
    }];
}


- (void)showAnimation{
    
    [kAppWindow addSubview:self];
    self.frame = kAppWindow.bounds;
    
    [self setNeedsLayout];
    [self layoutIfNeeded];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.bgViewTopConstraint uninstall];
        [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
            self.bgViewBottomConstraint = make.bottom.mas_offset(0);
            
        }];
        [UIView animateWithDuration:0.2 animations:^{
            [self setNeedsLayout];
            [self layoutIfNeeded];
            [self setBackgroundColor:[UIColor.blackColor colorWithAlphaComponent:0.3]];
        }];
    });
//    [self scorllToCurrentValue];
    [self getCountryList];
}




-(UIView*)addressView
{
    UIView *bgView = kView;
    bgView.backgroundColor = UIColor.whiteColor;
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.showsHorizontalScrollIndicator = NO;
    [bgView addSubview:scrollView];
    self.scrollView = scrollView;
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    UIView *containView = kView;
    containView.backgroundColor = UIColor.whiteColor;
    [scrollView addSubview:containView];
    self.containView = containView;
    [containView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
        make.height.equalTo(bgView);
    }];
    
    UIView *line = kView;
    line.backgroundColor = CFCellLineColor;
    [bgView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.offset(1);
        make.bottom.mas_offset(0);
    }];
    return bgView;
}

-(void)updateAddressView
{
    for (QMUILabel *lab in self.labelArr) {
        lab.hidden = YES;
    }
    [self.containView qmui_removeAllSubviews];
    kWeakSelf;
    __block UIView *lastLab;
    [self.selectArr removeAllObjects];
    if (self.countryModel) {
        [self.selectArr addObject:self.countryModel];
    }
    if (self.stateModel) {
        [self.selectArr addObject:self.stateModel];
    }
    if (self.cityModel) {
        [self.selectArr addObject:self.cityModel];
    }
    [self.selectArr enumerateObjectsUsingBlock:^(RHCountryModel*  _Nonnull orgModel, NSUInteger idx, BOOL * _Nonnull stop) {
        QMUILabel *lab = [weakSelf.labelArr safeObjectAtIndex:idx];
       
        lab.hidden = NO;
        if (lab==nil) {
            lab = [QMUILabel labelWithText:orgModel.name font:kSYSTEMFONT(16) textColor:kCOLOR_HEX(@"#05C79D")];
            lab.tag = idx;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]init];
            [tap addTarget:self action:@selector(tapAction:)];
            [lab addGestureRecognizer:tap];
            [weakSelf.labelArr addObject:lab];
        }
        lab.text = orgModel.name;
        if (idx == weakSelf.selectArr.count - 1) {
            lab.textColor = kCOLOR_HEX(@"#303133");
            lab.userInteractionEnabled = NO;
        }else{
            lab.textColor = kCOLOR_HEX(@"#05C79D");
            lab.text = [NSString stringWithFormat:@"%@ /",lab.text];
            lab.attributedText = [NSString attributeStringWithContent:lab.text attriFont:lab.font attriColor:kCOLOR_HEX(@"#8B8D92") attriKey:@"/"];
            
            lab.userInteractionEnabled = YES;
        }
     
        [weakSelf.containView addSubview:lab];
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            if (lastLab) {
                make.left.equalTo(lastLab.mas_right).offset(5);
            }else{
                make.left.mas_offset(10);
            }
            make.centerY.mas_offset(0);
//            make.width.offset(width+10);
        }];
        lastLab = lab;
    }];
    [lastLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-10);
    }];
    
}

-(void)tapAction:(UIGestureRecognizer*)gesture
{
   
    QMUILabel *lab = (QMUILabel*)gesture.view;
    NSObject *model = [self.selectArr safeObjectAtIndex:lab.tag];
    if ([model isEqual:self.stateModel]) {
        self.cityModel = nil;

    }
    if ([model isEqual:self.countryModel]) {
        self.stateModel = nil;
        self.stateArr = nil;
        self.cityModel = nil;
    }
    [self updateAddressView];
    [self.tableView reloadData];
    
    
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.cityModel) {
        return self.cityArr.count;
    }
    if (self.stateModel) {
        return self.stateArr.count;
    }
    return self.countryArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
   
    return nil;
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"city"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"city"];
        UIView *line = kView;
        line.backgroundColor = kCOLOR_HEX(@"#EBEEF4");
        [cell.contentView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.right.mas_offset(-15);
            make.bottom.mas_offset(0);
            make.height.offset(1);
        }];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = kSYSTEMFONT(14);
    cell.textLabel.textColor = kCOLOR_HEX(@"#303133");
    if (self.cityModel) {
        RHCityModel *model = [self.cityArr safeObjectAtIndex:indexPath.row];
        cell.textLabel.text = model.name;
    }else if (self.stateModel) {
        RHStateModel *model = [self.stateArr safeObjectAtIndex:indexPath.row];
        cell.textLabel.text = model.name;
    }else if (self.countryModel){
        RHCountryModel *model = [self.countryArr safeObjectAtIndex:indexPath.row];
        cell.textLabel.text = model.name;
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    if (self.cityModel) {//已经选了城市
        RHCityModel *cityModel = [self.cityArr safeObjectAtIndex:indexPath.row];
        self.cityModel = cityModel;
       
       
    }else if (self.stateModel){
        RHStateModel *stateModel = [self.stateArr safeObjectAtIndex:indexPath.row];
        self.stateModel = stateModel;
        [self getCityListWithCountryCode:self.countryModel.code stateCode:self.stateModel.code];
       
    }else if(self.countryModel){
        RHCountryModel *countryModel = [self.countryArr safeObjectAtIndex:indexPath.row];
        self.countryModel = countryModel;
        [self getStateListWithCountryCode:self.countryModel.code];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        CGFloat offset = self.scrollView.contentSize.width - self.scrollView.width;
        if (offset<0) {
            offset = 0;
        }
        [self.scrollView setContentOffset:CGPointMake(offset, 0) animated:YES];
    });
    
    [tableView reloadData];
    [self updateAddressView];
}

-(void)getCountryList
{
    [QMUITips showLoadingInView:kAppWindow];
    [RHCountryModel startGetWithCompletionAPIKey:H_getCountryList argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            self.countryArr = resultModel.data;
            self.countryModel = [self.countryArr firstObject];
            [self.tableView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

-(void)getStateListWithCountryCode:(NSString *)countryCode
{
    [QMUITips showLoadingInView:kAppWindow];
    [RHStateModel startGetWithCompletionAPIKey:H_getStateList argument:@{@"countryCode":countryCode} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            self.stateArr = resultModel.data;
            self.stateModel = [self.stateArr firstObject];
            [self.tableView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

-(void)getCityListWithCountryCode:(NSString *)countryCode stateCode:(NSString*)stateCode
{
    [QMUITips showLoadingInView:kAppWindow];
    [RHCityModel startGetWithCompletionAPIKey:H_getCityList argument:@{@"countryCode":countryCode,@"stateCode":stateCode} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            self.cityArr = resultModel.data;
            self.cityModel = [self.cityArr firstObject];
            [self.tableView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}
@end
